#pragma once

#include <iostream>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "log.hpp"

#define defaultAddr "0.0.0.0"

const int backlog = 10;

class tcpserver
{
private:
    int _listenfd;
    int _port;
    static tcpserver* svr;
private:
    tcpserver(int port) : _port(port)
    { 
        Socket();
        Bind();
        Listen();
        Log(INFO, "Tcp init right!");
    }
    tcpserver(const tcpserver& self) = delete;
public:
    static tcpserver* Getinstance(int port)
    {
        static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
        if(svr == nullptr)
        {
            pthread_mutex_lock(&lock);
            if(svr == nullptr)
            {
                svr = new tcpserver(port);
            }
            pthread_mutex_unlock(&lock);
        }
        return svr;
    }
    int Fd()
    {
        return _listenfd;
    }
    void Socket()
    {
        _listenfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_listenfd < 0)
        {
            Log(FATAL, "socket fail");
            exit(1);
        }
	int opt = 1;
	setsockopt(_listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt));
    }
    void Bind()
    {
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = inet_addr(defaultAddr);
        if(bind(_listenfd, (struct sockaddr *)&server, sizeof(server)) < 0)
        {
            Log(FATAL, "bind fail");
            exit(2);
        }
    }
    void Listen()
    {
        if(listen(_listenfd, backlog) < 0)
        {
            Log(FATAL, "listen fail");
            exit(3);
        }
    }
    ~tcpserver() { }
};

tcpserver* tcpserver::svr = nullptr;
